import { View, Button } from '@tarojs/components';
import './index.scss';
import IconFont from '../../iconfont';
import { useEffect, useState } from 'react';
import Taro from '@tarojs/taro';
import CourseCard from '../../../components/Card/CourseCard';
import { STATUS, STATUS_NAME_EN, courseInfo } from '../../../configProvider';

const Course = () => {
  const [courseList, setCourseList] = useState<courseInfo[]>([]);
  const [status, setStatus] = useState(-1);
  const createAttendCheck = () => {
    Taro.navigateTo({ url: '../newCheck/index' })
  }
  useEffect(() => {
    Taro.getStorage({
      key: 'status',
      success: (status) => {
        setStatus(status.data);
        Taro.getStorage({
          key: 'code',
          success: function (res) {
            console.log(res.data)
            Taro.cloud.callFunction({
              // 要调用的云函数名称
              name: 'getCourseList',
              // 传递给云函数的event参数
              data: {
                code: res.data,
                status: STATUS_NAME_EN[status.data]
              }
            }).then((res: any) => {
              console.log('courses', res.result)
              setCourseList(res.result)
            }).catch(err => {
              console.log('fail to call getCourseList', err)
            })
          },
          fail: (res) => {
            console.log('fail to get code', res)
          }
        })
      }
    })
  }, [])

  const handleClick = (index: number) => {
    if (status === STATUS.ADMIN) {
      doEdit(index);
    } else if (status === STATUS.TEACHER) {
      doActive(index);
    } else if (status === STATUS.INSTRUCTOR) {
      doView(index);
    } else if (status === STATUS.STUDENT) {
      doLeave(index);
    }
  }

  const doEdit = (index: number) => {
    Taro.navigateTo({
      url: '../editCourse/index?course=' + JSON.stringify(courseList[index])
    })
  }
  const doActive = (index: number) => {
    const selectedCourse = courseList[index];
    const courseId = selectedCourse._id;
    const isActive = selectedCourse.active;

    if (!isActive) {
      Taro.showModal({
        title: '开启点名',
        content: `开启“${selectedCourse.courseName}”的签到？`,
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定');
            Taro.navigateTo({
              url: `../startCheck/index?courseId=${selectedCourse._id}`
            })
            // Taro.cloud.callFunction({
            //   name: 'changeCourseState',
            //   data: {
            //     _id: courseId,
            //     action: 'start',
            //   },
            // }).then((res) => {
            //   console.log('changeCourseState', res);
            //   Taro.showToast({
            //     title: '开启成功',
            //     icon: 'success',
            //     duration: 1000,
            //   }).then(() => {
            //     setTimeout(() => {
            //       Taro.reLaunch({ url: '../index/index' });
            //     }, 1000);
            //   });
            // }).catch((err) => {
            //   console.log('fail to call changeCourseState', err);
            // });
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        },
      });
    } else {
      Taro.showModal({
        title: '关闭点名',
        content: `关闭“${selectedCourse.courseName}”的签到？`,
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定');
            Taro.cloud.callFunction({
              name: 'changeCourseState',
              data: {
                _id: courseId,
                action: 'stop',
              },
            }).then((res) => {
              console.log('changeCourseState', res);
              Taro.showToast({
                title: '关闭成功',
                icon: 'success',
                duration: 1000,
              }).then(() => {
                setTimeout(() => {
                  Taro.reLaunch({ url: '../index/index' });
                }, 1000);
              });
            }).catch((err) => {
              console.log('fail to call changeCourseState', err);
            });
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        },
      });
    }
  };

  const doView = (index: number) => { }
  const doLeave = (index: number) => {
    const course: courseInfo = courseList[index];
    if (!course.active) {
      Taro.showModal({
        title: '请假',
        content: `申请课程'${course.courseName}'的请假?`,
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            sendLeave(course._id);
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  }
  const sendLeave = (courseId: string) => {
    Taro.getStorage({
      key: 'code',
      success: (res) => {
        Taro.cloud.callFunction({
          // 要调用的云函数名称
          name: 'doLeave',
          // 传递给云函数的event参数
          data: {
            _id: courseId,
            code: res.data,
          }
        }).then((res: any) => {
          // output: res.result === 3
          console.log('success', res.result)
          if (res.result.success) {
            Taro.showToast({
              title: '请假成功',
              icon: 'success',
              duration: 2000,
            });
            setTimeout(() => {
              Taro.navigateBack();
            }, 2000);
          } else {
            Taro.showModal({
              title: '请加失败',
              content: res.result.error
            })
          }
        }).catch(err => {
          console.log('fail to call doLeave', err)
        })
      }
    })

  }

  return <>
    {status === STATUS.ADMIN && <Button className='common-button new-button' onClick={createAttendCheck}>新建课程</Button>}
    {status === STATUS.TEACHER && <View className='common-title'>点击课程开启/关闭点名</View>}
    {status === STATUS.STUDENT && <View className='common-title'>点击未开启点名的课程可以请假</View>}
    {courseList.length !== 0
      // 有数据时渲染列表
      ? <View className='courses-list'>
        {courseList.map((value, index) =>
          <CourseCard name={value.courseName} startTime={value.startTime} endTime={value.endTime}
            weekday={value.weekday} teacher={value.teacher} startDate={value.startDate}
            endDate={value.endDate} status={status} active={value.active}
            onClick={() => { handleClick(index) }} />
        )}
      </View>
      // 没有课程时的tip
      : <View className='no-cheak'>
        <View className='no-cheak-tips no-cheak-tips-icon'>
          <IconFont name='check-rectangle' size={200} color='#ccc' />
        </View>
        <View className='no-cheak-tips no-cheak-tips-1'>暂无课程</View>
      </View>
    }
  </>
}
export default Course;
